<?php
namespace app\admin\controller;


use app\common\model\Area;
use app\common\model\Group;
use app\common\model\Order;
use think\Db;
use Upload;

class Main extends Base
{

     public function __construct()
    {
        parent::__construct();
        $this->isLogin();
    }


    /**
     * @route('main/index')
     */
    public function index()
    {
        // 获取权限
        $auth = $this->_licenseid['license_data'];
        $menu = model('License')
            ->with(
                ['subs'=>function($query)use($auth){$query

                    ->where('status',1)
                    ->where('sysnav_id', '<>', 0)
                    ->where('license_id','in',$auth)
                    ->order('sort','asc');
                }])
            ->where('license_id','in', $auth)
            ->where('sysnav_id',0)
            ->where('status',1)
            ->order('sort','asc')
            ->select();

        $tvar = array(
            "title" => "首页",
            "time"  => time(),
            "menu"  => $menu,
        );
        $this->assign("data", $tvar);
        return $this->fetch('main/index');
    }

    /**
     * @route('main/welcome')
     */
    public function welcome()
    {
        $tvar = array(
            "title" => "首页",
            "time"  => time(),
        );
        $this->assign("data", $tvar);
        return $this->fetch('main/welcome1');
    }


    /**
     * @route('main/authlist')
     * 权限管理
     */
    public function authlist()
    {
        $groupModel = new Group();

        if(request()->isAjax()){
            if(input('type') == 0){
                $group_id = input('group_id');
                $auth = $groupModel->getOne(array('group_id' => $group_id),'license_data')['license_data'];
                $auths = explode(',',$auth);
                $this->success('','',$auths);
            }else{
                $id = input('id');

                // 获取用户组ID
                $group_id = $id['user'];
                // 删除掉数组第一个
                unset($id['user']);
                // 重新格式化数组成为字符串
                $id = implode(",", $id);
                $rs = $groupModel->edit(array("license_data" => $id,), $group_id);
                if($rs === false){
                    $this->error($groupModel->getError());
                }
                $this->success('操作成功');
            }
        }

        // 获取管理组列表
        $rs = $groupModel->get_list();

        // 获取模块列表
        $auth = $this->_licenseid['license_data'];
        $menu = model('License')
            ->with(
                ['subs'=>function($query)use($auth){$query

                    ->where('status',1)
                    ->where('sysnav_id', '<>', 0)
//                    ->where('license_id','in',$auth)
                    ->order('sort','asc');
                }])
//            ->where('license_id','in', $auth)
            ->where('sysnav_id',0)
            ->where('status',1)
            ->order('sort','asc')
            ->select();


        $tvar = array(
            "title" => "权限管理",
            "time"  => time(),
            "group" => $rs,
        );
        $this->assign('menu', $menu);
        $this->assign('data', $tvar);
        return $this->fetch('main/authlist');
    }


    /**
     * @route('main/quit')
     */
    public function quit()
    {
        cookie('name', null);
        $this->redirect('/login');
    }


    /**
     * 富文本上传图片接口
     * @route('main/ueditor')
     */
    public function ueditor()
    {

        $res = Upload::FileUpload('file','ueditor',1024*1024*20);
        if(!$res['data']){
            $this->result('','2',$res['msg']);
        }
        $data['src'] = $_SERVER['HTTP_ORIGIN']."/".$res['data']['file_path'];
        $this->result($data,'0','上传成功');
    }



    /**
     * 上传图片接口
     * @route('main/upload')
     */
    public function upload()
    {

        $res = Upload::FileUpload('file','top',1024*1024*10);
        if(!$res['data']){
            $this->result('','-1','上传出错');
        }
        $data['src'] = $res['data']['file_path'];
        $this->result($data,'1','上传成功');
    }


    /**
     * @route('main/region')
     * 地区联动
     */
    public function Region()
    {
        $AreaModel = new Area();

        $param = input();

        $cond['pid'] = $param['type_id'];

        $data = $AreaModel->get_list($cond,'id, name');

        $this->result($data, 1,'操作成功');
    }


    /**
     * @route('main/statistics')
     * 统计订单
     */
    public function Statistics()
    {
        $orderModel = new Order();
        $userModel = new \app\common\model\User();

        // 用户
        $user = $userModel->count('user_id');



        // 订单收入金额
        $order = $orderModel->where('order_type',1)->where('order_status','in','2,3,4')->sum('pay_amount');
        $service = $orderModel->where('order_type',3)->where('order_status','in','2,3,4')->sum('pay_amount');

        $day = date("Y-m-d", time());
        // 获取当月所有数据
        $orderwhere = [
            ['order_status', 'in', '2,3,4'],
            ['format_time', 'like', "%".$day."%"]
        ];
        $all = $orderModel->where($orderwhere)->sum('pay_amount');

        $time = strtotime(date("Y-m-d", time()));
        $alluser = $userModel->where('add_time', '>', $time)->count('user_id');

        $arr = [
            'user'      => $user,
            'order'     => $order,
            'service'   => $service,
            'allday'   => $all,
            'alluser'   => $alluser,
        ];

        $this->result($arr,1);
    }



    /**
     * @route('main/month')
     * 月营收入
     */
    public function Month()
    {
        $orderModel = new Order();

        $month = input('month');
        if(!$month){
            $month  = date("Y-m", time());
        }
        $time = strtotime($month);

        $t = date("t", $time);

        // 获取当月所有数据
        $orderwhere = [
            ['order_type', '=', '1'],
            ['order_status', 'in', '2,3,4'],
            ['format_time', 'like', "%".$month."%"]
        ];

        $order = $orderModel->where($orderwhere)->field('format_time,pay_amount')->select()->toArray();

        $servicewhere = [
            ['order_type', '=', '3'],
            ['order_status', 'in', '2,3,4'],
            ['format_time', 'like', "%".$month."%"]
        ];
        $service = $orderModel->where($servicewhere)->field('format_time,pay_amount')->select()->toArray();

        $days[] = array();
        $orders[] = array();
        $services[] = array();
        for ($i = 0; $i < $t; $i++){

            if ($i < 9) {
                $daystr = "0" . ($i+1);
            } else {
                $daystr = $i+1;
            }
            $days[$i] = $daystr;
            $orders[$i] = 0;
            $services[$i] = 0;

            $day = $month.'-'.$daystr;
            if($order){
                $money = 0;
                foreach ($order as $key => $val){
                    if($day == $val['format_time']){
                        $money = calculate([$money,$val['pay_amount']],'+');
                    }
                    $orders[$i] = $money;
                }
            }

            if($service){
                $money = 0;
                foreach ($service as $key => $val){
                    if($day == $val['format_time']){
                        $money = calculate([$money,$val['pay_amount']],'+');
                    }
                    $services[$i] = $money;
                }
            }
        }
        $arr = [
            'day' => $days,
            'order' => $orders,
            'service'   => $services
        ];

        $this->result($arr,1);
    }


    /**
     * @route('main/year')
     * 年营收入
     */
    public function Year()
    {
        $orderModel = new Order();

        $year = input('year');
        if(!$year){
            $year  = date("Y", time());
        }

        $orderwhere = [
            ['order_type', '=', '1'],
            ['order_status', 'in', '2,3,4'],
            ['format_time', 'like', "%".$year."%"]
        ];
        $order = $orderModel->where($orderwhere)->field("pay_amount,FROM_UNIXTIME(order_time, '%Y-%m') as time")->select()->toArray();

        $servicewhere = [
            ['order_type', '=', '3'],
            ['order_status', 'in', '2,3,4'],
            ['format_time', 'like', "%".$year."%"]
        ];
        $service = $orderModel->where($servicewhere)->field("pay_amount,FROM_UNIXTIME(order_time, '%Y-%m') as time")->select()->toArray();

        $days[] = array();
        $orders[] = array();
        $services[] = array();
        for ($i = 0; $i < 12; $i++){
            if ($i < 9) {
                $daystr = "0" . ($i+1);
            } else {
                $daystr = $i + 1;
            }
            $days[$i] = $daystr;
            $orders[$i] = 0;
            $services[$i] = 0;


            $month = $year.'-'.$daystr;

            if($order){
                $money = 0;
                foreach ($order as $key => $val){
                    if($month == $val['time']){
                        $money = calculate([$money,$val['pay_amount']],'+');
                    }
                    $orders[$i] = $money;
                }
            }

            if($service){
                $money = 0;
                foreach ($service as $key => $val){
                    if($month == $val['time']){
                        $money = calculate([$money,$val['pay_amount']],'+');
                    }
                    $services[$i] = $money;
                }
            }
        }


        $arr = [
            'data'  => $days,
            'order' => $orders,
            'service'   => $services
        ];

        $this->result($arr,1);
    }

}
